import Vue from 'vue'
import VueRouter from 'vue-router'
// import Login from '@/views/Login/LoginView.vue'
// import Layout from '@/views/Layout/LayoutView.vue'
// import Home from '@/views/Home/HomeView.vue'
// import User from '@/views/User/UserView.vue'
// import Search from '@/views/Search/SearchView.vue'
// import SearchResult from '@/views/Search/SeachResult.vue'
// import ArticleDetail from '@/views/ArticleDetail/ArticleDetail.vue'
// import UserEditor from '@/views/User/UserEdit.vue'
// import Chat from '@/views/Chat/ChatView.vue'

import { getToken } from '@/utils/token.js'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: () =>
      import(
        /* webpackChunkName: "group-user" */ '@/views/Login/LoginView.vue'
      ),
    // 路由独享守卫
    beforeEnter(to, from, next) {
      if (getToken()?.length > 0) {
        next('/layout/home')
      } else {
        next()
      }
    }
  },
  {
    path: '/layout',
    component: () =>
      import(
        /* webpackChunkName: "group-user" */ '@/views/Layout/LayoutView.vue'
      ),
    children: [
      {
        path: 'home',
        component: () =>
          import(
            /* webpackChunkName: "group-user" */ '@/views/Home/HomeView.vue'
          ),
        meta: {
          scrollT: 0 // 保存首页离开时, 滚动条位置
        }
      },
      {
        path: 'user',
        component: () =>
          import(
            /* webpackChunkName: "group-user" */ '@/views/User/UserView.vue'
          )
      }
    ]
  },
  {
    path: '/search',
    component: () =>
      import(
        /* webpackChunkName: "group-user" */ '@/views/Search/SearchView.vue'
      )
  },

  {
    path: '/search_result/:keywords',
    component: () =>
      import(
        /* webpackChunkName: "group-user" */ '@/views/Search/SeachResult.vue'
      )
  },
  {
    path: '/detail',
    component: () =>
      import(
        /* webpackChunkName: "group-user" */ '@/views/ArticleDetail/ArticleDetail.vue'
      )
  },
  {
    path: '/user_editor',
    component: () =>
      import(/* webpackChunkName: "group-user" */ '@/views/User/UserEdit.vue')
  },
  {
    path: '/chat',
    component: () =>
      import(/* webpackChunkName: "group-user" */ '@/views/Chat/ChatView.vue')
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  if (to.path === '/login') return next()
  // 获取登录后的token值
  const tokenStr = getToken()
  if (!tokenStr) return next('/login')
  next()
})

export default router
